<?php

namespace  App\Http\Controllers\V1;

use App\Helpers\DateUtils;
use App\Helpers\RestResponseFactory;
use App\Helpers\RestUtils;
use App\Http\Controllers\Controller;
use App\Models\Factory\SmsFactory;
use App\Models\Factory\UserFactory;
use App\Services\Core\Sms\Dahan\DahanService;
use Illuminate\Http\Request;
/**
 * Class GeetesController
 * @package App\Http\Controllers\V1
 * 短信
 */
class SmsController extends  Controller
{

    /**
     * 发送短信
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function SendCode(Request $request)
    {


        #接收参数
        $mobile = $request->input('userphone');
        $data = $request ->all();
//
//        #检查一分钟是否有重复发送
//        $check = SmsFactory::checkCodeExistenceTime($mobile);
//
//        if (!$check)
//        {
//            return RestResponseFactory::ok(RestUtils::getStdObj(), RestUtils::getErrorMessage(1201), 1201);
//        }
//
//        $ipNums = SmsFactory::limitIp();
//
//        if ($ipNums >= 18)
//        {
//            return RestResponseFactory::ok(RestUtils::getStdObj(), RestUtils::getErrorMessage(7109), 7109);
//        }
//        $mobileNums =SmsFactory::limitMobile($mobile);
//
//        if ($mobileNums >= 6 )
//        {
//            return RestResponseFactory::ok(RestUtils::getStdObj(), RestUtils::getErrorMessage(7109), 7109);
//        }

        #检查用户是否存在
        $user =  UserFactory::getUserByMobile($mobile);
        $userData['userphone'] = $mobile;

        #如果不存在的话，则向用户主表中插入一条数据，
        if ($user==false || empty($user->token)) {

            UserFactory::createUser($userData['userphone'],$data['terminal'],$data['app_name']);
//            #发送短信
//            $re =DahanService::send($mobile);
            #返回结果
//            if ($re == false) {
//
//                return RestResponseFactory::ok(RestUtils::getStdObj(), RestUtils::getErrorMessage(1205), 1205);
//            }

            $info['is_user'] = 1;
            $info['userphone'] = $data['userphone'];
            //根据用户的主键生成token
            $info['token'] =  $token['token'] = md5("anwen".time().$user['id']);
//            $token['lass_time'] = DateUtils::getToday();
            //把用户的唯一标识保存到数据库内
            UserFactory::addUserTokenByMobile($data['userphone'],$token);
            return RestResponseFactory::ok($info,200);
        }

        //根据用户的主键生成token
        $token['lass_time'] = DateUtils::getToday();
        //把用户的唯一标识保存到数据库内
        $result = UserFactory::addUserTokenByMobile($data['userphone'],$token);
        $token['token'] = $user->token;

        if($result)
        {

            return RestResponseFactory::ok($token,200);

        }

        return RestResponseFactory::ok(RestUtils::getStdObj(), RestUtils::getErrorMessage(1101), 1101);


    }




}